const { tk } = require('../conf/index')
const jwt = require('jsonwebtoken');
const myDb = require('../libs/mydb')
const mytk = require('../libs/mytoken')
module.exports = function (req, res, next) {
    if (req.moduleName == 'api') {
        if (tk.path.indexOf(req.url) < 0) {
            if (req.headers['user-token']) {
                jwt.verify(req.headers['user-token'], tk.secret, async (err, dacode) => {
                    if (err) {
                        // console.log(err);
                        res.send({
                            code: 407,
                            msg: 'Token expired'
                        })
                    } else {
                        let str = ''
                        await myDb.singleSearch("ac_user", "u_token", ` WHERE u_name='${String(dacode.uname)}'`)
                            .then(
                                result => {
                                    str = result[0].u_token;
                                }
                            )
                        if (mytk.check(req.headers['user-token']).iat != mytk.check(str).iat) {
                            res.send({
                                code: 408,
                                msg: 'Tokens are different'
                            })
                        } else {
                            next()
                        }

                    }
                })
            } else {
                res.send({
                    code: 400,
                    msg: `Failed to user-token`
                })
            }
        } else {
            next()
        }

    } else {
        next()
    }

}